package com.abe.bathsystem.base;

import android.os.Bundle;
import android.view.MotionEvent;

import com.abe.bathsystem.utils.ConstantBath;
import com.abe.libcore.utils.normal.CommonUtils;

import java.util.Timer;
import java.util.TimerTask;

public abstract class TimeOutAutoMvpBaseActivity extends AutoMvpActivity {

    public abstract void timeOut();

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //有按下动作时取消定时
                stopTimer();
                break;
            case MotionEvent.ACTION_UP:
                //抬起时启动定时
                startTimer();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    //计时器
    private Timer timer;
    private TimerTask task;
    private int timeOutNum = 0;

    private void initTimer() {
        timer = new Timer();
        task = new TimeOutTask();
    }

    //启动计时器
    private void startTimer() {
        /*
         * java.util.Timer.schedule(TimerTask task, long delay, long period)：
         * 这个方法是说，delay/1000秒后执行task,然后进过period/1000秒再次执行task，
         * 这个用于循环任务，执行无数次，当然，你可以用timer.cancel();取消计时器的执行。
         */
        initTimer();
        try {
            timer.schedule(task, 1000, 1000);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            initTimer();
            timer.schedule(task, 1000, 1000);
        }
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
        }
        //置零
        timeOutNum = 0;
    }

    private void destroyTimer() {
        timer = null;
        task = null;
    }


    protected class TimeOutTask extends TimerTask {

        @Override
        public void run() {
            timeOutNum++;
            showTime(timeOutNum);
            if (timeOutNum * 1000 >= ManagerTimer.autoLockTime()) {
                timeOut();
                timeOutNum = 0;
            }
        }
    }

    //前台Activity无操作时间广播
    private void showTime(int time) {
        String ACTION_NO_EVENT_TIME = "com.abe.bathsystem.noevent.time";
        Bundle bundle = new Bundle();
        bundle.putInt("time", time);
        CommonUtils.sendBroadcast(ACTION_NO_EVENT_TIME, bundle);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startTimer();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //当activity不在前台是停止定时
        stopTimer();
    }

    @Override
    public void onDestroy() {
        //销毁时停止定时
        stopTimer();
        destroyTimer();
        super.onDestroy();
    }
}